package com.umeng.community.example.Utils;

import android.content.Context;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.qianxx.base.IConstants;
import com.qianxx.base.Urls;
import com.qianxx.base.request.Config;
import com.qianxx.base.request.RM;
import com.qianxx.base.request.RequestBean;
import com.qianxx.base.request.RequestCallback;
import com.qianxx.base.request.RequestUtil;
import com.umeng.community.example.bean.MyBean;
import com.umeng.community.example.bean.MyInfo;

import java.util.HashMap;

/**
 * Created by zhangbingyong on 16/5/19.
 */
public class UserRequestUtils implements RequestCallback {
    private UserRequestUtils() {
    }

    private static UserRequestUtils requestUtils;
    private static Context mContext;
    protected RequestQueue mRequest; // 请求队列对象
    private MyInfo info;

    public static UserRequestUtils getInstance(Context context) {

        if (requestUtils == null) {
            synchronized (UserRequestUtils.class) {
                if (requestUtils == null) {
                    requestUtils = new UserRequestUtils();

                }
            }
        }
        mContext = context;

        return requestUtils;
    }

    /**
     * 获取用户的信息
     */
    public void loadInfo(GetUserInfoListener getUserInfoListener) {
        this.getUserInfoListener = getUserInfoListener;
        HashMap<String, String> map = new HashMap<>();
        requestDataWithoutLoading(IConstants.MORE, Urls.USER_GET, RM.POST, MyBean.class, map);
    }

    @Override
    public void requestSuccess(RequestBean baseBean, Config config) {
        MyBean bean = (MyBean) baseBean;
        info = bean.getData();
        getUserInfoListener.setUserInfo(info);
    }


    /**
     * 不带loading指示的数据请求
     */
    private void requestDataWithoutLoading(String requestTag, String url,
                                           RM method, Class<? extends RequestBean> bean,
                                           HashMap<String, String> params) {
        if (mRequest == null) {
            mRequest = Volley.newRequestQueue(mContext);
        }
        RequestUtil.requestData(mRequest, requestTag, url, method, bean,
                params, this, new Config().setShowLoading(false));
    }


    @Override
    public void requestFail(RequestBean bean, Config config) {

    }

    @Override
    public void requestTokenInvalid(String requestTag, Config config) {

    }

    private GetUserInfoListener getUserInfoListener;

    public GetUserInfoListener getGetUserInfoListener() {
        return getUserInfoListener;
    }

    public void setGetUserInfoListener(GetUserInfoListener getUserInfoListener) {
        this.getUserInfoListener = getUserInfoListener;
    }

    public interface GetUserInfoListener{
        public void setUserInfo(MyInfo myInfo);
    }
}
